
def bind(ip, port):
    import usocket
    use.usock = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM)
    use.usock.setsockopt(usocket.SOL_SOCKET, usocket.SO_REUSEADDR, 1)
    use.usock.setblocking(0)
    use.usock.bind( (ip, port) )
    return use.usock

def ap(essid=b'ap', password=b'', channel=9, authmode=0):
    import network
    try:use.network.disconnect()
    except:pass
    use.network.active(False)
    Time.sleep(2)

    use.PEERS={}

    use.ap = network.WLAN(network.AP_IF)
    use.ap.active(True)
    use.ap.config(essid=essid, authmode=authmode, password=password, channel=channel)

    use.IP = use.ap.ifconfig()[0]
    #bind(use.IP,8266)
    return bind('0.0.0.0',8266)

def sta_down():
    try:use.network.disconnect()
    except:pass
    try:use.network.active(False)
    except:pass

#async
def sta(essid=b'ap',password=b'', ap='192.168.4.1', port= 8266):
    use.network.active(True)
    use.network.connect(essid,password)
    while True:
        use.IP = use.network.ifconfig()[0]
        #still on primary ap ?
        if use.IP[0]!='0':
            if not use.IP.startswith('192.168.1.'):break
        Time.sleep(1)
    #bind('0.0.0.0', port)
    #bind(use.IP, port)

#
#def wlan_sta(essid="", password="", ap=False, tmout=30, dlay=.25):
#    if not essid:
#        with open("/network", "rb") as f:
#
#            def gl():
#                return f.readline().decode().strip()
#
#            use.network = gl()
#            essid = use.network
#            use.password = gl()
#            password = use.password
#            use.srv = gl()
#
#    if use.board:
#        import network
#
#        if not ap:
#            network.WLAN(network.AP_IF).active(False)
#        wlan = network.WLAN(network.STA_IF)
#
#        print("", "=" * 79, "", sep="\n")
#
#        builtins.wlan0 = wlan
#        tmout = int(tmout * (1.0 / dlay))
#
#        while not wlan.isconnected() and tmout > 0:
#            Time.sleep(dlay)
#            print(".", end="")
#            tmout -= 1
#
#        if not wlan.isconnected():
#            wlan.active(True)
#            print("Wlan[ %s ]" % essid, end=" ")
#            wlan.connect(essid, password)
#
#            while not wlan.isconnected() and tmout > 0:
#                Time.sleep(dlay)
#                print(".", end="")
#                tmout -= 1
#        else:
#            print("", "(reco : %s)" % essid, end=" ")
#
#        use.IP = wlan.ifconfig()[0]
#        print("", use.IP)
#        return 1
